
using System;
using UMC.Bridge;
using UMC.Net;
using UMC.Web;
using UMC.Web.UI;

namespace UMC.ITME.Activities
{

    [Apiumc("ITME", "Device", Desc = "资源设备", Auth = WebAuthType.Guest)]
    class SiteDeviceActivity : UMC.Web.WebActivity
    {
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var key = this.AsyncDialog("Key", g => this.DialogValue("Secret"));
            var SessionKey = this.AsyncDialog("SessionKey", g => this.DialogValue(Utility.Guid(Guid.NewGuid())));

            var clientInfo = Utility.FromBase64String(key);
            var idKey = new byte[8];
            clientInfo.AsSpan(0, 6).CopyTo(idKey.AsSpan(2));
            var deviceId = BitConverter.ToUInt64(idKey);

            var device = UMC.Data.HotCache.Get(new Entities.Device { Id = deviceId });
            if (device == null)
            {
                this.Prompt("无此设备");
            }
            if (Security.AuthManager.Authorization(this.Context.Token.Identity(), 0, new Net.StringValue($"Device/{deviceId}"), out var isBiometric) > 0)
            {
                if (isBiometric)
                {
                    this.AsyncDialog("Biometric", "System", "Biometric", true);
                }
                var time = Utility.IntParse(UIDialog.AsyncDialog(this.Context, "ExpirationTime", r =>
                {
                    var form = new UIFormDialog();
                    form.Title = "资源授权";

                    var txtValue = form.AddTextValue().Put("终端地址", new System.Net.IPAddress(clientInfo.AsSpan(6)).ToString()).Put("授权资源", device.Caption).Put("资源地址", $"{device.Ip}:{device.Port}");
                    txtValue.Put("资源类型", device.Type.ToString());
                    if (String.IsNullOrEmpty(device.Desc) == false)
                    {
                        txtValue.Put("资源描述", device.Desc);
                    }

                    form.AddRadio("会话保持", "ExpirationTime").Put("1小时", "1", true).Put("2小时", "2").Put("5小时", "5")
                    .Put("24小时", "24");

                    form.Submit("确认授权");
                    return form;
                }), 1);
                var uString = new StringValue(this.Context.Token.Username);//.UTF8()
                var umd5 = Utility.MD5(uString.Span);//.Span, bufer.AsSpan(8));

                var t = new byte[clientInfo.Length - 2];
                BitConverter.TryWriteBytes(t.AsSpan(t.Length - 4), Utility.IntParse(umd5));

                clientInfo.AsSpan(6).CopyTo(t);

                var sockUser = SocksUser.Cache.Get(new SocksUser
                {
                    ClientIP = new StringValue(t),
                    Port = new StringValue(idKey, 6, 2),
                    UserAgent = new StringValue(idKey, 2, 4)
                });
                if (sockUser != null)
                {

                    BitConverter.TryWriteBytes(sockUser.ExpirationTime.Span, Utility.TimeSpan());
                    BitConverter.TryWriteBytes(sockUser.ActiveTime.Span, Utility.TimeSpan(DateTime.Now.AddHours(time)));
                }
                else
                {
                    SocksUser.Cache.Put(new SocksUser
                    {
                        ClientIP = new StringValue(t),
                        Port = new StringValue(idKey, 6, 2),
                        UserAgent = new StringValue(idKey, 2, 4),
                        Username = uString,
                        ActiveTime = Utility.TimeSpan().StringValue(),
                        SessionKey = new StringValue(Utility.FromBase64String(SessionKey)),
                        ExpirationTime = Utility.TimeSpan(DateTime.Now.AddHours(time)).StringValue()
                    });
                }

                var appId = Utility.Parse36Encode(Utility.IntParse(WebServlet.AppId.Span));
                UMC.Host.HttpWebSocket.Send(Utility.Guid(key, true).Value, "{\"type\":\"user\",\"value\":\"" + this.Context.Token.Username + "@" + appId + "\"}");

                this.Prompt("提示", "授权成功");
            }
            else
            {
                this.Prompt("您没有权限访问此设备");
            }
        }
    }
}
